import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class SalesReport {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat sdfWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void generateReport(int type, Scanner scanner) {
        String sql = "";
        String title = "";
        Date startDate = null;
        Date endDate = null;

        switch (type) {
            case 1: // 今日
                title = "今日销售报表";
                startDate = getStartOfDay(new Date());
                endDate = getEndOfDay(new Date());
                break;
            case 2: // 本周
                title = "本周销售报表";
                startDate = getStartOfWeek(new Date());
                endDate = getEndOfDay(new Date());
                break;
            case 3: // 本月
                title = "本月销售报表";
                startDate = getStartOfMonth(new Date());
                endDate = getEndOfDay(new Date());
                break;
            case 4: // 自定义
                System.out.print("请输入开始日期(格式: yyyy-MM-dd): ");
                String startStr = scanner.nextLine();
                System.out.print("请输入结束日期(格式: yyyy-MM-dd): ");
                String endStr = scanner.nextLine();

                try {
                    startDate = sdf.parse(startStr);
                    endDate = sdf.parse(endStr);
                    endDate = getEndOfDay(endDate);
                    title = startStr + " 至 " + endStr + " 销售报表";
                } catch (ParseException e) {
                    System.out.println("日期格式错误");
                    return;
                }
                break;
        }

        // 查询这段时间的销售数据
        sql = "SELECT m.name, COUNT(t.id) as ticket_count, SUM(t.price * (LENGTH(t.seat_ids) - LENGTH(REPLACE(t.seat_ids, ',', '')) + 1)) as total_sales " +
                "FROM tickets t " +
                "JOIN shows s ON t.show_id = s.id " +
                "JOIN movies m ON s.movie_id = m.id " +
                "WHERE t.purchase_time BETWEEN ? AND ? " +
                "GROUP BY m.name " +
                "ORDER BY total_sales DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setTimestamp(1, new java.sql.Timestamp(startDate.getTime()));
            pstmt.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));

            ResultSet rs = pstmt.executeQuery();

            System.out.println("\n=== " + title + " ===");
            System.out.println("日期范围: " + sdf.format(startDate) + " 至 " + sdf.format(endDate));
            System.out.println("------------------------------------------------");
            System.out.printf("%-30s %-15s %-15s%n", "电影名称", "售票数量", "销售总额(元)");
            System.out.println("------------------------------------------------");

            int totalTickets = 0;
            double totalSales = 0;

            while (rs.next()) {
                String movieName = rs.getString("name");
                int ticketCount = rs.getInt("ticket_count");
                double sales = rs.getDouble("total_sales");

                totalTickets += ticketCount;
                totalSales += sales;

                System.out.printf("%-30s %-15d %-15.2f%n", movieName, ticketCount, sales);
            }

            System.out.println("------------------------------------------------");
            System.out.printf("%-30s %-15d %-15.2f%n", "总计", totalTickets, totalSales);

        } catch (SQLException e) {
            System.err.println("生成销售报表失败: " + e.getMessage());
        }
    }

    // 获取一天的开始时间 (00:00:00)
    private Date getStartOfDay(Date date) {
        try {
            return sdf.parse(sdf.format(date));
        } catch (ParseException e) {
            return date;
        }
    }

    // 获取一天的结束时间 (23:59:59)
    private Date getEndOfDay(Date date) {
        try {
            Date start = sdf.parse(sdf.format(date));
            return new Date(start.getTime() + 24 * 60 * 60 * 1000 - 1);
        } catch (ParseException e) {
            return date;
        }
    }

    // 获取本周的开始时间 (周一 00:00:00)
    private Date getStartOfWeek(Date date) {
        try {
            Date startOfDay = getStartOfDay(date);
            int dayOfWeek = new java.util.Calendar.Builder().setInstant(startOfDay).build().get(java.util.Calendar.DAY_OF_WEEK);
            // 周日是1，周一是2，...，周六是7
            int daysToSubtract = (dayOfWeek == 1) ? 6 : (dayOfWeek - 2);
            return new Date(startOfDay.getTime() - daysToSubtract * 24 * 60 * 60 * 1000);
        } catch (Exception e) {
            return date;
        }
    }

    // 获取本月的开始时间 (1号 00:00:00)
    private Date getStartOfMonth(Date date) {
        try {
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTime(date);
            cal.set(java.util.Calendar.DAY_OF_MONTH, 1);
            return getStartOfDay(cal.getTime());
        } catch (Exception e) {
            return date;
        }
    }
}
